import csv

def menu():
    print("1. 计算BMR和BMI")
    print("2. 退出")
    choice = int(input("请选择："))
    return choice

def calculate_bmr(gender, age, height, weight):
    if gender == '男':
        bmr = 10 * weight + 6.25 * height - 5 * age + 5
    else:
        bmr = 10 * weight + 6.25 * height - 5 * age - 161
    return bmr

def calculate_bmi(height, weight):
    return weight / (height * height)

def health_advice(bmr, bmi):
    if bmi < 18.5:
        print("您的体重过轻，请注意保持健康的饮食习惯和增加营养摄入。")
    elif 18.5 <= bmi < 24.9:
        print("您的体重正常，继续保持健康的生活方式。")
    elif 25 <= bmi < 29.9:
        print("您属于超重范围，请注意控制饮食，增加运动。")
    else:
        print("您属于肥胖范围，建议咨询医生，制定科学的减肥计划。")

    if bmr < 1200 or bmr > 2500:
        print("您的基础代谢率（BMR）不在正常范围内，建议咨询医生进行进一步评估。")

def write_to_csv(gender, age, height, weight, bmr):
    with open('user_data.csv', mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([gender, age, height, weight, bmr])

def count():
    while True:
        gender = input("请输入性别（男/女）： ")
        if gender in ['男', '女']:
            break
        else:
            print("不支持该性别。")

    while True:
        try:
            age = int(input("请输入年龄： "))
            if age > 0:
                break
            else:
                print("错误年龄，请输入正整数。")
        except ValueError:
            print("错误输入，请输入数字。")

    while True:
        try:
            height = float(input("请输入身高（米）： "))
            if height > 0:
                break
            else:
                print("错误身高，请输入正数。")
        except ValueError:
            print("错误输入，请输入数字。")

    while True:
        try:
            weight = float(input("请输入体重（公斤）： "))
            if weight > 0:
                break
            else:
                print("错误体重，请输入正数。")
        except ValueError:
            print("错误输入，请输入数字。")

    bmr = calculate_bmr(gender, age, height, weight)
    bmi = calculate_bmi(height, weight)

    print(f"BMR指数为：{bmr}")
    print(f"BMI指数为：{bmi}")

    health_advice(bmr, bmi)

    write_to_csv(gender, age, height, weight, bmr)

    while True:
        continue_choice = input("是否继续？（是/否）： ").lower()
        if continue_choice in ['是', 'yes']:
            break
        elif continue_choice in ['否', 'no']:
            print("程序已退出。")
            return
        else:
            print("无效选择，请输入 '是' 或 '否'。")

def main():
    while True:
        choice = menu()

        if choice == 1:
            count()
        elif choice == 2:
            print("程序已退出。")
            break
        else:
            print("无效的选择，请重新输入。")

if __name__ == "__main__":
    main()
